import { useUserStore } from '@/store/modules/user';
import { setCache } from '.';

// 基础URL配置，可根据环境变量调整
const baseURL = import.meta.env.VITE_APP_API_HOST ;

export enum ContentTypeEnum {
  // json
  JSON = 'application/json',
  // form-urlencoded qs
  FORM_URLENCODED = 'application/x-www-form-urlencoded',
  // form-data  upload
  FORM_DATA = 'multipart/form-data',
}
// 请求配置接口定义
interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS';
  data?: any;
  headers?: Record<string, string>;
  loading?: boolean;
  showError?: boolean;
}

// 响应数据接口定义
interface ResponseData<T = any> {
  info: string;
  code: number;
  message: string;
  data: T;
}

/**
 * 统一请求函数
 * @param options 请求配置
 */
export const request = async <T = any>(options: RequestOptions): Promise<T> => {
  // 默认显示loading
  if (options.loading !== false) {
    uni.showLoading({ title: '加载中...', mask: true });
  }
  const userStore = useUserStore();
  // 获取token
  const token = userStore.token;

  // 默认请求头
  const headers = {
    'Content-Type': ContentTypeEnum.FORM_URLENCODED,
    'Authorization':token,
    ...options.headers,
    // 添加token
  };
  // #ifdef H5
  options.data ={
    ...options.data,
    equipment_type:2
  }
  // #endif

  try {
    // 发起请求
    const res = await uni.request({
      url: baseURL + options.url,
      method: options.method || 'GET',
      data: options.data,
      header: headers
    });

    // 请求失败（网络错误）
    if (res.errMsg && res.errMsg !== 'request:ok') {
      throw new Error(res.errMsg || '网络请求失败');
    }
    // 处理响应数据
    const response = res.data as ResponseData<T>;
    // 业务逻辑错误
    if (response.code !== 1) {
      // 未登录
      if (response.code === 401) {
        // 清除token并跳转登录页
        // #ifdef H5
        setCache('redirectUrl', window.location.href);
        // #endif
        uni.removeStorageSync('token');
        setTimeout(() => {
          uni.reLaunch({ url: '/pages/login/index' });
        }, 1000);
      }

      // 显示错误信息
      if (options.showError !== false) {
        uni.showToast({
          title: response.info || '操作失败',
          icon: 'none',
          duration: 3000
        });
      }

      throw new Error(response.info || `请求错误: ${response.code}`);
    }

    return response.data;
  } catch (error) {
    // 显示错误信息
    if (options.showError !== false) {
      uni.showToast({
        title: error instanceof Error ? error.message : '未知错误',
        icon: 'none',
        duration: 3000
      });
    }
    throw error;
  } finally {
    // 隐藏loading
    if (options.loading !== false) {
      uni.hideLoading();
    }
  }
};

/**
 * GET请求
 * @param url 请求地址
 * @param params 查询参数
 * @param options 其他配置
 */
export const get = <T = any>(
  url: string,
  params?: Record<string, any>,
  options?: Omit<RequestOptions, 'url' | 'method' | 'data'>
) => {
  // 处理查询参数
  if (params) {
    const queryString = Object.entries(params)
      .filter(([_, value]) => value !== undefined && value !== null && value !== '')
      .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
      .join('&');

    url += queryString ? (url.includes('?') ? `&${queryString}` : `?${queryString}`) : '';
  }

  return request<T>({ ...options, url, method: 'GET' });
};

/**
 * POST请求
 * @param url 请求地址
 * @param data 请求体数据
 * @param options 其他配置
 */
export const post = <T = any>(
  url: string,
  data?: any,
  options?: Omit<RequestOptions, 'url' | 'method' | 'data'>
) => {
  return request<T>({ ...options, url, method: 'POST', data });
};

/**
 * PUT请求
 * @param url 请求地址
 * @param data 请求体数据
 * @param options 其他配置
 */
export const put = <T = any>(
  url: string,
  data?: any,
  options?: Omit<RequestOptions, 'url' | 'method' | 'data'>
) => {
  return request<T>({ ...options, url, method: 'PUT', data });
};

/**
 * DELETE请求
 * @param url 请求地址
 * @param data 请求体数据
 * @param options 其他配置
 */
export const del = <T = any>(
  url: string,
  data?: any,
  options?: Omit<RequestOptions, 'url' | 'method' | 'data'>
) => {
  return request<T>({ ...options, url, method: 'DELETE', data });
};

// 导出默认请求实例
export default {
  request,
  get,
  post,
  put,
  delete: del
};